﻿/*v1.1*/

/**
参数：参数1：保留的小数位数   参数2：数值类型(0不限制1正数-1负数) 参数2：失去焦点事件
* 限制输入框只能输入数字(JQuery插件)
*
* @example $("#txtId").limitNumber()
*
* @example $("#txtId").limitNumber(4,0) or $("#txtId").limitNumber({'scale': 4,'numberType':0})
*
* var blurEvent=function(){doSomething}
* @example $("#txtId").limitNumber(4,0,onblurEvent) or $("#txtId").limitNumber({'scale': 4,'numberType':0,"onblurEvent":blurEvent})
*
* @example $(".txtCss").limitNumber()
**/
$.fn.limitNumber = function () {
    var args = arguments;
    var json = typeof (args[0]) == "object";
    var scale = json ? args[0].scale : args[0];
    var numberType = json ? args[0].numberType : args[1];
    var onblurEvent = json ? args[0].onblurEvent : args[2];
    scale = scale || 0;
    numberType = numberType || 0;
    onblurEvent = onblurEvent || null;
    $(this).css("ime-mode", "disabled");
    var keys = new Array(8, 9, 35, 36, 37, 38, 39, 40, 46);
    this.bind("keydown", function (e) {
        e = window.event || e;
        var code = e.which || e.keyCode;
        if (e.shiftKey) {
            return false;
        }
        var idx = Array.indexOf(keys, code);
        if (idx != -1) {
            return true;
        }
        var value = this.value;
        //.号处理
        if (code == 190 || code == 110) {
            if (scale == 0 || value.indexOf(".") != -1) {
                return false;
            }
            return true;

        }
        //负号处理
        else if (code == 189 || code == 109) {
            if (numberType != 1) {//允许负数
                if (value.indexOf("-") != -1) {
                    return false;
                }
                return true;
            }
            return false;
        }
        else {
            if ((code >= 48 && code <= 57) || (code >= 96 && code <= 105)) {
                if (scale > 0 && value.indexOf(".") != -1) {
                    //var reg = new RegExp("^([+-]?)[0-9]+(\.[0-9]{0," + (scale - 1) + "})?$");
                    //var selText = getSelection();
                    //                    if (selText != value && !reg.test(value)) {
                    //                        return false;
                    //                    }
                }
                return true;
            }
            return false;
        }
    });
    this.bind("blur", function () {
        if (this.value.lastIndexOf(".") == (this.value.length - 1)) {
            this.value = this.value.substr(0, this.value.length - 1);
        } else if (isNaN(this.value)) {
            this.value = "";
        } else {
            var value = this.value;
            if (scale > 0 && value.indexOf(".") != -1) {
                var reg = new RegExp("^([+-]?)[0-9]+(\.[0-9]{0," + scale + "})?$");
                if (!reg.test(value)) {
                    this.value = format(value, scale);
                }
            }
            if (numberType == -1 && value.indexOf("-") == -1) {//只能负数
                this.value = "-" + this.value;
            }
        }
        if (onblurEvent != null)
            onblurEvent();
    });
    this.bind("paste", function () {
        var s = window.clipboardData.getData('text');
        if (!/\D/.test(s));
        value = s.replace(/^0*/, '');
        return false;
    });
    this.bind("dragenter", function () {
        return false;
    });
    var format = function (value, scale) {
        return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
    }
    var getSelection = function () {
        if (window.getSelection) {
            return window.getSelection();
        }
        if (document.selection) {
            return document.selection.createRange().text;
        }
        return "";
    };
    Array.indexOf = function (array, value) {
        for (var i = 0; i < array.length; i++) {
            if (value == array[i]) {
                return i;
            }
        }
        return -1;
    }
};

function WinOpen(url, width, height) {
    var left, top;
    left = (screen.width - width) / 2;
    top = (screen.height - height) / 2;
    if (width > screen.availWidth)
        width = screen.availWidth;
    if (height > screen.availHeight)
        height = screen.availHeight;
    window.open(url, "", "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",status=0,toolbar=0,scrollbars=1,location=0,directories=0,menubar=0,resizable=1");
}

//打开新窗口
function WinOpenFull(url) {
    if (getBrowser(false) == "ie") {
        var new_window = window.open(url, "", "top=0,left=0,status=0,toolbar=0,scrollbars=1,location=0,directories=0,menubar=0,resizable=1");
        new_window.resizeTo(screen.availWidth, screen.availHeight);
    }
    else
        var new_window = window.open(url);
}
/*
by yvan 2014-1-8
功能：获取浏览器类别（兼容ie11）
参数：returnVersions 返回的名称是否附加版本号
注意：返回值全部为小写
*/
function getBrowser(returnVersions) {
    var userAgent = navigator.userAgent
    var browser;
    var version;
    var ua = userAgent.toLowerCase();
    var browserMatch = uaMatch(userAgent.toLowerCase());
    if (browserMatch.browser) {
        browser = browserMatch.browser;
        version = browserMatch.version;
    }
    if (returnVersions)
        return browser.toLowerCase() + version;
    else
        return browser.toLowerCase();
}
//判断浏览器：匹配正则表达式
function uaMatch(ua) {
    var rMsie = /(msie\s|trident.*rv:)([\w.]+)/,
                rFirefox = /(firefox)\/([\w.]+)/,
                rOpera = /(opera).+version\/([\w.]+)/,
                rChrome = /(chrome)\/([\w.]+)/,
                rSafari = /version\/([\w.]+).*(safari)/;
    var match = rMsie.exec(ua);
    if (match != null) {
        return { browser: "IE", version: match[2] || "0" };
    }
    var match = rFirefox.exec(ua);
    if (match != null) {
        return { browser: match[1] || "", version: match[2] || "0" };
    }
    var match = rOpera.exec(ua);
    if (match != null) {
        return { browser: match[1] || "", version: match[2] || "0" };
    }
    var match = rChrome.exec(ua);
    if (match != null) {
        return { browser: match[1] || "", version: match[2] || "0" };
    }
    var match = rSafari.exec(ua);
    if (match != null) {
        return { browser: match[2] || "", version: match[1] || "0" };
    }
    if (match != null) {
        return { browser: "", version: "0" };
    }
}
window.translateTextFromJson = function (str) {
    return (str && str.length > 0) ? str.replace(/&apos;/g, "'").replace(/&quot;/g, "\"").replace(/&0D;/g, "\r").replace(/&0A;/g, "\n").replace(/&amp;/g, "&") : str;
};

//验证url
function testUrl(str) {
    var reg = /^http[s]?:\/\/([\w-]+\.)+[\w-]+([\w-./?%&=]*)?/; return reg.test(str); 
}

//验证扩展
//内置基本的datatype类型有： * | *6-16 | n | n6-16 | s | s6-18 | p | m | e | url
//*：检测是否有输入，可以输入任何字符，不留空即可通过验证；
//*6-16：检测是否为6到16位任意字符；
//n：数字类型；
//n6-16：6到16位数字；
//s：字符串类型；
//s6-18：6到18位字符串；
//p：验证是否为邮政编码；
//m：手机号码格式；
//e：email格式；
//url：验证字符串是否为网址。
function getDatatype(){
    return {
        //英文、数字、下划线或中短线组成
        "code": /^[u9fa5_a-zA-Z0-9-]+$/,
        //大于0的整数
        "intege1": /^[1-9]\d*$/,
        //大于等于0的整数
        "intege2": /^[0-9]\d*$/,
        //大于等于0的数值
        "decmal4": /(^-?\d\d*[\.|,]\d*$)|(^-?\d\d*$)|(^-?[\.|,]\d\d*$)/,
        "Mobile": /^1[3|4|5|7|8]\d{9}$/
    }
}

function alertNoimg(msg, func){
    layer.alert(msg, -1, func);
}

////弹出警告  msg:提示信息
//function alertInfo(msg, func) {
//    layer.alert(msg, 8, func);
//}
////成功提示  msg:提示信息 func 函数对象
//function alertSucc(msg, func) {
//    layer.alert(msg, 9,func);
//}

//弹出警告  msg:提示信息
function alertInfo(msg, func) {
    //可自动关闭
    layer.msg(msg, { icon: 8, shade: 0.4, time: 2000, shadeClose:true }, func);

    //不自动关闭
    //layer.alert(msg, { icon: 8}, func);
}

//成功提示  msg:提示信息 func 函数对象
function alertSucc(msg, func) {
    layer.msg(msg, { icon: 1, shade: 0.4, time: 2000, shadeClose: true }, func);

    //layer.alert(msg, { icon: 1 }, func);
}

//询问提示框 msg:提示信息  func：点击确认后的回调函数
function confirmShow(msg, func,func1){
    layer.confirm(msg, { icon: 3, title: '提示' }, func, func1)
}

//加载层
function showload(msg,num){
    layer.load(msg, num);
}

//iframe显示层 title：弹出层标题   url：iframe链接 width：宽度（auto为默认1000）  height：高度（auto为自动）
var ifmIndex;
//function showIframe(title, url, width, height, isShowOnParent) {
//    if(isShowOnParent){
//        ifmIndex=parent.$.layer({
//            type: 2,
//            maxmin: false,
//            shadeClose: false,
//            title: title,
//            shade: [0.1, 'black'],
//            offset: ['20px', ''],
//            area: [(width=='auto'?'1000':width)+'px', (height=='auto'?($(window).height() - 50):height) + 'px'],
//            iframe: { src: url }
//        });
//    }
//    else {
//        ifmIndex=$.layer({
//            type: 2,
//            maxmin: false,
//            shadeClose: false,
//            title: title,
//            shade: [0.1, 'black'],
//            offset: ['20px', ''],
//            area: [(width=='auto'?'1000':width)+'px', (height=='auto'?($(window).height() - 50):height) + 'px'],
//            iframe: { src: url }
//        });
//    }
//    return ifmIndex;
//}
function showIframe(title, url, width, height, isShowOnParent, isCenter) {
    if (isShowOnParent) {
        ifmIndex = parent.layer.open({
            type: 2,
            title: title,
            shadeClose: false,
            shade: 0.2,
            offset: isCenter ? "auto" : ['5px', '5px'],
            maxmin: true,
            shift:2,//1~6 css动画效果
            area: [(width == 'auto' ? '1000' : width) + 'px', (height == 'auto' ? ($(window).height() - 50) : height) + 'px'],
            content: url //iframe的url
        });
    }
    else {
        ifmIndex = layer.open({
            type: 2,
            title: title,
            shadeClose: false,
            shade: 0.2,
            offset: isCenter ? "auto" : ['5px', '5px'],
            maxmin:true,
            shift: 2,//1~6 css动画效果
            area: [(width == 'auto' ? '1000' : width) + 'px', (height == 'auto' ? ($(window).height() - 50) : height) + 'px'],
            content: url //iframe的url
        });
    }
    //if (isFullScreen) {
    //    layer.full(ifmIndex);
    //}
    return ifmIndex;
}
function showIframeFull(title, url) {

        ifmIndex = layer.open({
            type: 2,
            title: title,
            shadeClose: false,
            shade: 0.2,
            //offset: isCenter ? "auto" : ['5px', '5px'],
            maxmin: true,
            shift: 2,//1~6 css动画效果
            //area: [(width == 'auto' ? '1000' : width) + 'px', (height == 'auto' ? ($(window).height() - 50) : height) + 'px'],
            area: ['100%', '100%'],
            content: url //iframe的url
        });
    
    //if (isFullScreen) {
    //    layer.full(ifmIndex);
    //}
    return ifmIndex;
}


//div显示层 title：弹出层标题   domStr：document元素(.class) 
//width：宽度（auto为默认1000）  height：高度（auto为自动）defaultClose：是否有默认关闭
//function showDialog(title, domStr, width, height, defaultClose) {
//    ifmIndex=$.layer({
//        type: 1,
//        maxmin: false,
//        shadeClose: false,
//        title: title,
//        closeBtn: [0, defaultClose], //去掉默认关闭按钮
//        shade: [0.1, '#fff'],
//        offset: ['20px', ''],
//        area: [(width=='auto'?'1000':width)+'px', (height=='auto'?($(window).height() - 50):height) + 'px'],
//        page: {dom : domStr}

//    });
//    return ifmIndex;
//}
function showDialog(title, domStr, width, height, defaultClose) {
    ifmIndex = layer.open({
        type: 1,
        maxmin: false,
        shadeClose: false,
        title: title,
        //closeBtn: [0, defaultClose], //去掉默认关闭按钮
        shade: 0.3,
        //offset: ['20px', ''],
        content: $(domStr),
        area: [(width == 'auto' ? '1000' : width) + 'px', (height == 'auto' ? ($(window).height() - 50) : height) + 'px']
        //,page: { dom: domStr }
        
    });
    return ifmIndex;
}
//关闭窗口
function closeIframe(ind){
    layer.close(ind);
}
//关闭窗口
function closeWin(){
//    if(isShowOnParent){
//        alert(ifmIndex)
//        parent.layer.close(ifmIndex);
//    }
    //    else
        layer.close(ifmIndex);
}
//关闭所有窗口
function closeAll(){
    layer.closeAll();
}

//显示树形选择器
//id:选择器编号  fillFuncName：填充函数名称  title：显示的选择器名称 checkMode：选择模式，0为单选，1多选  OtherPara:其它参数
function showTreeSelector(title, id, fillFuncName, checkMode, OtherPara) {
    showIframe(title, "/sys/SelectTool/TreeSelector?id=" + id + "&CheckMode=" + (checkMode ? checkMode : "0") + "&FunctionName=" + fillFuncName + "&OtherPara=" + (OtherPara ? OtherPara : "") + "&r=" + (Math.random() * (100000 + 1)), "500", "400");
}
//显示列表选择器
//id:选择器编号  fillFuncName：填充函数名称  title：显示的选择器名称 checkMode：选择模式，0为单选，1多选  OtherPara:其它参数
function showGridSelector(title,id,gid, apiurl) {
    showIframe(title, "../html/gridSelector/gridSelector.html?id=" + id+ "&gid=" +gid + "&apiurl=" + apiurl + "&r=" + (Math.random() * (100000 + 1)), "650", "550");
}

//类似<a>打开
function openLikeA(url, target){   
    WinOpenFull(url);
}

function getEditorToolbar(){
//    return [
//	        { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-','NewPage', 'Preview', 'Print', '-', 'Templates' ] },
//	        { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
//	        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ], items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
//	        //{ name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
//	        '/',
//	        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
//	        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] },
//	        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
//	        { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] },
//	        '/',
//	        { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
//	        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
//	        { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
//	        { name: 'others', items: [ '-' ] }
//            ];
    return [
	        { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'Source', '-','NewPage', 'Preview', 'Print'] },
	        { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: ['Undo', 'Redo' ] },
	        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
	        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
	        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
	        { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'PageBreak', 'Iframe' ] },
	        { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
	        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
	        { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
	        { name: 'others', items: [ '-' ] }
            ];
}